package com.example.springboot3demo.util;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JsonToInsertSqlUtil {

    public static List<String> jsonArrayToInsertSql(String jsonArray) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonArray);
            List<String> insertSqlList = new ArrayList<>();
            if (jsonNode.isArray()) {
                for (JsonNode element : jsonNode) {
                    StringBuilder columns = new StringBuilder();
                    StringBuilder values = new StringBuilder();
                    java.util.Iterator<String> fieldNamesIterator = element.fieldNames();
                    while (fieldNamesIterator.hasNext()) {
                        String fieldName = fieldNamesIterator.next();
                        if (columns.length() > 0) {
                            columns.append(", ");
                            values.append(", ");
                        }
                        String columnName = camelToUnderline(fieldName);
                        columns.append(columnName);
                        JsonNode valueNode = element.get(fieldName);
                        if (valueNode.isTextual()) {
                            values.append("'").append(valueNode.textValue()).append("'");
                        } else if (valueNode.isNumber()) {
                            values.append(valueNode.numberValue());
                        } else if (valueNode.isBoolean()) {
                            values.append(valueNode.booleanValue()? 1 : 0);
                        } else if (valueNode.isNull()) {
                            values.append("NULL");
                        }
                    }
                    String insertSql = "INSERT INTO bond_access_record (" + columns + ") VALUES (" + values + ")";
                    insertSqlList.add(insertSql);
                }
            }
            System.out.println(insertSqlList.stream().collect(Collectors.joining(";")));
            return insertSqlList;
        } catch (IOException e) {
            throw new RuntimeException("解析JSON数组失败", e);
        }
    }

    private static String camelToUnderline(String camelCase) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < camelCase.length(); i++) {
            char c = camelCase.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    result.append('_');
                }
                result.append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

}